﻿using IdentityServer4Blazor.Shared;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;

namespace IdentityServer4Blazor.Server.Filter
{
    public class ResultFilter : ActionFilterAttribute
    {

        public ResultFilter()
        {
        }
        public override void OnResultExecuted(ResultExecutedContext context)
        {

            base.OnResultExecuted(context);
        }
        public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if (context.ModelState.IsValid)
            {
                var res = context.Result.GetType();
                if (!res.Equals(typeof(EmptyResult))&&!res.Equals(typeof(SignOutResult))&&!res.Equals(typeof(RedirectResult)))
                {
                    var value = (context.Result as dynamic)?.Value;
                    Console.WriteLine(value);
                    //var res = JsonSerializer.Serialize(new ReponseModel { Success = true, Data = value, Msg = "" });
                    var serializeOptions = new JsonSerializerOptions { PropertyNamingPolicy =null };
                    context.Result = new JsonResult(new ReponseModel { Success = true, Data = value, Msg = "" }, serializeOptions);
                    
                    context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
                }
                base.OnResultExecuting(context);
            }
            else
            {
                var list = new List<string>();
                foreach (var item in context.ModelState.Values)
                {
                    foreach (var error in item.Errors)
                    {
                        list.Add(error.ErrorMessage);
                    }
                }
                context.Result = new JsonResult(new ReponseModel { Success = false, Data = list, Msg = "参数错误" });
                context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
            }
            await base.OnResultExecutionAsync(context, next);
        }
        //public override void OnResultExecuting(ResultExecutingContext context)
        //{

        //}
        public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            return base.OnActionExecutionAsync(context, next);
        }
    }
}
